package com.gepengjun.lims.controler;


import com.baomidou.mybatisplus.plugins.Page;
import com.gepengjun.lims.config.lims.LimsProperties;
import com.gepengjun.lims.entity.Orgnazation;
import com.gepengjun.lims.entity.RefRoleUser;
import com.gepengjun.lims.entity.Role;
import com.gepengjun.lims.entity.User;
import com.gepengjun.lims.service.OrgnazationService;
import com.gepengjun.lims.service.RefRoleUserService;
import com.gepengjun.lims.service.RoleService;
import com.gepengjun.lims.service.UserService;
import com.gepengjun.lims.util.FileUtil;
import com.gepengjun.lims.util.JsonResult.Result;
import com.gepengjun.lims.util.JsonResult.ResultCode;
import com.gepengjun.lims.util.JsonResult.ResultUtil;
import com.gepengjun.lims.util.common.CommonUtil;
import com.gepengjun.lims.util.common.DataType;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import org.springframework.stereotype.Controller;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author jun
 * @since 2018-08-19
 */
@Controller
@RequestMapping("/lims/user")
public class UserController extends  BaseController{
    protected static final Logger logger = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private OrgnazationService orgnazationService;

    @Autowired
    private RefRoleUserService refRoleUserService;


    @Autowired
    private LimsProperties limsProperties;

    @RequestMapping(value = "/findById",method = RequestMethod.GET)
    public String findById(User user, ModelMap modelMap){
        user = userService.selectById(user.getUserId());
        Orgnazation dept = orgnazationService.findDeptByUserId(user.getUserId());
        user.setDept(dept);
        user.setCompany(orgnazationService.selectById(dept.getParentId()));
        modelMap.addAttribute("user",user);
        return "user/userInfo";
    }

    @RequestMapping(value = "/updPasswordPage",method = RequestMethod.GET)
    public String updPasswordPage(User user, ModelMap modelMap){
        user = userService.selectById(user.getUserId());
        modelMap.addAttribute("user",user);
        return "user/updPassword";
    }

    @RequestMapping(value = "/updPassword",method = RequestMethod.POST)
    @ResponseBody
    public Boolean updPassword(User user){
        return userService.updPassword(user.getUserId(),user.getUsername(),user.getPassword());
    }

    @RequestMapping(value = "/userList",method = RequestMethod.GET)
    public String userList(User user,String deptName,String companyName, Page<User> page, ModelMap modelMap){
        Orgnazation dept = new Orgnazation();
        dept.setOrgName(deptName);
        Orgnazation company = new Orgnazation();
        company.setOrgName(companyName);
        user.setDept(dept);
        user.setCompany(company);
        page = userService.findUserPage(page,user);
        modelMap.addAttribute("user",user);
        modelMap.addAttribute("page",page);
        return "user/userList";
    }
    @RequestMapping(value = "/userAddPage",method = RequestMethod.GET)
    public String userAddPage(ModelMap modelMap){
        List<Orgnazation> companyList = orgnazationService.findAllAvailableCompany();
        List<Role> roleList = roleService.findAllAvailableRole();
        modelMap.addAttribute("companyList",companyList);
        modelMap.addAttribute("roleList",roleList);
        return "user/userAdd";
    }

    @RequestMapping(value = "/judgeUsernameAvailable",method = RequestMethod.POST)
    @ResponseBody
    public Boolean judgeUsernameAvailable(User user){
        return userService.judgeUsernameAvailable(user.getUsername());
    }


    @RequestMapping(value = "/addUser",method = RequestMethod.POST)
    @ResponseBody
    public Boolean addUser(User user,String roleIds){
        logger.info("addUser:"+user.toString());
        logger.info("addUser:roleIds--"+roleIds);
        return userService.addUser(user,roleIds);
    }

    @RequestMapping(value = "/disableUser",method = RequestMethod.POST)
    @ResponseBody
    public Boolean disableUser(User user){
        return userService.disableUser(user);
    }

    @RequestMapping(value = "/ableUser",method = RequestMethod.POST)
    @ResponseBody
    public Boolean ableUser(User user){
        return userService.ableUser(user);
    }

    @GetMapping("/updUserPage")
    public String updUserPage(User user,ModelMap map){
        logger.debug("updUserPage:"+user.getUserId());
        user = userService.selectById(user.getUserId());
        Orgnazation dept = orgnazationService.findDeptByUserId(user.getUserId());
        user.setDept(dept);
        user.setCompany(orgnazationService.selectById(dept.getParentId()));
        List<Orgnazation> companyList = orgnazationService.findAllAvailableCompany();
        List<Orgnazation> deptList = orgnazationService.findAllAvailableDept();
        List<Role> roleList = roleService.findAllAvailableRole();
        Map<String,Object> params = new HashMap<>();
        params.put("user_id",user.getUserId());
        List<RefRoleUser> refRoleUserList = refRoleUserService.selectByMap(params);
        List<Long> userRoleIds = new ArrayList<>();
        for (RefRoleUser refRoleUser:refRoleUserList){
            userRoleIds.add(refRoleUser.getRoleId());
        }
        map.addAttribute("user",user);
        map.addAttribute("companyList",companyList);
        map.addAttribute("deptList",deptList);
        map.addAttribute("roleList",roleList);
        map.addAttribute("userRoleIds",userRoleIds);
        return "user/updUser";
    }

    @PostMapping("/updUser")
    @ResponseBody
    public  Boolean updUser(User user,String roleIds){
        return userService.updUser(user,roleIds);
    }


    @GetMapping("/userBatchAddPage")
    public String userBatchAddPage(){
        return "user/userBatchAdd";
    }

    @GetMapping("/downloadUserAddTemplate")
    public void downloadUserAddTemplate(HttpServletResponse response) throws IOException{
        List<Orgnazation> deptList = orgnazationService.findAllAvailableDept();
        deptList = orgnazationService.initParent(deptList);
        List<Orgnazation> companyList = orgnazationService.findAllAvailableCompany();
        companyList = orgnazationService.initChildren(companyList);
        FileUtil.downloadUserAddTemplate(response,companyList);

    }

    @PostMapping("/batchAddUser")
    @ResponseBody
    public Result batchAddUser(MultipartFile file) throws IOException{
        String fileName = file.getOriginalFilename();
        String fileSaveName = String.valueOf(new Date().getTime())+fileName.substring(fileName.lastIndexOf("."));
        boolean result = FileUtil.saveFile(limsProperties.getBatchAddUserFilePaht(),fileSaveName,file.getBytes());
        if (result){

            Map<String,Object> readResult = userService.readFile(limsProperties.getBatchAddUserFilePaht(),fileSaveName);
            List<User> userList = (List<User>) readResult.get("userList");
            if (userList.size() < 1){
                return ResultUtil.error(-101,"导入失败,文件无数据");
            }
            //验证 上传的文件,有效性:用户名,部门编码,启用 是否为空;用户名是否有重复,是否可用;部门编码是否可用;
            Map<String,String> validateReuslt = userService.validateUserAddList(userList);
            if (validateReuslt.size() > 0){
                logger.info(validateReuslt.toString());
                //有错误信息的文件,不保留
                File file1 = new File(limsProperties.getBatchAddUserFilePaht()+fileSaveName);
                if (file1.exists()){
                    file1.delete();
                }

                return ResultUtil.error(ResultCode.PARAMETER_ERROR,"导入失败,数据有误",validateReuslt);
            }
            logger.info(userList.toString());
            logger.info(userService.toString());
            Boolean flag =  userService.insertBatch(userList);
            if (flag){
                return ResultUtil.success("批量导入用户成功");
            }else {
                return ResultUtil.error(-2,"导入数据失败");
            }

        }
        return null;
    }

    @PostMapping("/batchDisableUsers")
    @RequiresPermissions("user:del")
    @ResponseBody
    public boolean batchDisableUsers(String userIds){
        if (StringUtils.isNotEmpty(userIds)){
            List<Long> userIdList = (List<Long>)CommonUtil.covertArrayToList(userIds.split(","), DataType.ISLONG);
            return userService.batchDisableUsers(userIdList);
        }
        return  false;
    }

    @PostMapping("/batchAbleUsers")
    @ResponseBody
    @RequiresPermissions(value = "user:del")
    public boolean batchAbleUsers(String userIds){
        if (StringUtils.isNotEmpty(userIds)){
            List<Long> userIdList = (List<Long>)CommonUtil.covertArrayToList(userIds.split(","), DataType.ISLONG);
            return userService.batchAbleUsers(userIdList);
        }
        return  false;
    }
}

